<template>
  <el-select
    v-model="projectId"
    filterable
    :multiple="multiple"
    placeholder="请选择项目"
    style="width: 240px"
    :clearable="clearable"
  >
    <el-option
      v-for="item in xmList"
      :key="item.id"
      :label="item.name"
      :value="item.id"
    />
  </el-select>
</template>
<script>
import { allProject } from "@/api/project.ts";

export default {
  name: "projectSelector",
  props: {
    modelValue: [String, Array],
    multiple: {
      type: Boolean,
      default() {
        return false;
      }
    },
    selectFirst: {
      type: Boolean,
      default() {
        return false;
      }
    },
    clearable: {
      type: Boolean,
      default() {
        return false;
      }
    }
  },
  emits: ["update:modelValue", "change"],
  data() {
    return {
      xmList: [],
      keyword: "",
      projectId: this.modelValue
    };
  },
  watch: {
    projectId(nv) {
      console.log({ nv });
      this.$emit("update:modelValue", nv);
      this.$emit("change", this.xmList.filter(item => item.id === nv)?.[0]);
    }
  },
  async mounted() {
    let res = await allProject(1, 1000, this.keyword);
    if (res.code === 200) {
      this.xmList = res.data.records;
      console.log(this.xmList);
    }
    if (this.selectFirst && this.xmList?.length) {
      this.projectId = this.xmList[0].id;
    }
  }
};
</script>
